<template>
	<view class="login-container">
		<uni-forms ref="formRef" :rules="rules" :modelValue="ruleForm">
			<uni-forms-item label="手机号" required name="loginname">
				<uni-easyinput v-model="ruleForm.loginname" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item label="密码" required name="password">
				<uni-easyinput v-model="ruleForm.password" placeholder="请输入密码" type="password" />
			</uni-forms-item>
		</uni-forms>
		<van-button type="primary" block round @click="submit">登录</van-button>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue';
	import { login } from '../../api/user';
	import { useUserStore } from '../../stores/user';
	import { UserLogin } from '../../types/user'
	import { onShow } from '@dcloudio/uni-app'

	const formRef = ref(null)

	const store = useUserStore()

	let redirect = ''

	onShow(() => { })

	const ruleForm = ref({
		loginname: '17704051019',
		password: '123456'
	} as UserLogin)

	const rules = {
		loginname: {
			rules: [{
				required: true,
				errorMessage: '手机号不能为空'
			}, {
				pattern: /^1[3-9]\d{9}$/,
				errorMessage: '手机号不合法'
			}]
		},
		password: {
			rules: [{
				required: true,
				errorMessage: '密码不能为空'
			}, {
				pattern: /^\w{6,12}$/,
				errorMessage: '密码必须是6-12位'
			}]
		}
	}

	const submit = async () => {
		try {
			await formRef.value.validate()

			const res = await login({ loginname: ruleForm.value.loginname, password: ruleForm.value.password })
			if (res.code === 200) {
				store.setToken(res.data.token)
				uni.showToast({
					title: '登陆成功',
					icon: 'success',
					duration: 1000,
					success() {
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/home/home'
							})
							uni.setTabBarItem({
								index: 3,
								text: '我的'
							})
						}, 1000)
					}
				});
			} else {
				uni.showToast({
					title: res.message,
					icon: 'error'
				})
			}

		} catch (e) {
			console.log(e);
		}
	}
</script>

<style scoped lang="scss">
	.login-container {
		padding: 10px 10px
	}
</style>